package entity;

import java.util.HashMap;
import java.util.Set;

/**
 * 购物车类
 */
public class Cart {
    //购买的商品，建立集合类，键值是商品，值是购买数量
    private HashMap<Commodity,Integer> goods;
    //购物车总金额
    private double totalPrice;
    //构造方法
    public Cart(){
        goods=new HashMap<Commodity,Integer>();
        totalPrice=0.0;
    }

    public HashMap<Commodity, Integer> getGoods() {
        return goods;
    }

    public void setGoods(HashMap<Commodity, Integer> goods) {
        this.goods = goods;
    }

    public double getTotalPrice() {
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }
    //添加商品进购物车的方法
    public boolean addGoodsToCart(Commodity commodity,int number){
        //如果购物车已经有这个商品，则直接增加数量即可
        if (goods.containsKey(commodity)){
            goods.put(commodity,goods.get(commodity)+number);
        }else {
            goods.put(commodity,number);
        }

        //重新计算购物车总金额
        calTotalPrice();
        return true;
    }
    //删除商品的方法
    public boolean removeGoodsFromCart(Commodity commodity){
        goods.remove(commodity);
        //重新计算购物车总金额
        calTotalPrice();
        return true;
    }
    //统计商品总金额
    public double calTotalPrice(){
        double sum=0.0;
        //获取健的集合
        Set<Commodity> keys=goods.keySet();
        //通过for each遍历数据
        for (Object obj:keys){
            Commodity cd=(Commodity)obj;
            sum +=cd.getPrice()*goods.get(cd);
        }
        //设置购物车总金额
        this.setTotalPrice(sum);
        return this.getTotalPrice();
    }
    //测试购物车类是否正常
    /*
    public static void main(String[] args) {
        //创建商品对象，测试是否正常计算
        Commodity cd1=new Commodity(1,"李宁运动鞋",200,500,"001.jpg","温州");
        Commodity cd2=new Commodity(2,"小米手机",1000,200,"002.jpg","北京");
        //处理重复添加同一商品，购物车仅数量增加功能
        Commodity cd3=new Commodity(2,"小米手机",1000,200,"002.jpg","北京");
        Cart c=new Cart();
        c.addGoodsToCart(cd1,1);
        c.addGoodsToCart(cd2,2);
        c.addGoodsToCart(cd3,1);
        //遍历购买的商品,先得到键值对集合
        Set<Commodity> keys=c.getGoods().keySet();
        //通过for each遍历数据
        for (Object obj:keys){
            Commodity cd=(Commodity)obj;
            cd.getCommodity();
            System.out.println(",购物车数量："+c.getGoods().get(cd));
        }
        System.out.println("购物车总金额："+c.getTotalPrice());

    }
    */

}
